<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Business;
use addons\kuerp\model\BusinessStatus;
use addons\kuerp\model\ContractProduct;
use addons\kuerp\model\DeliveryProduct;
use addons\kuerp\model\Flows;
use addons\kuerp\model\FormApproval;
use addons\kuerp\model\Invoice;
use addons\kuerp\model\Message;
use addons\kuerp\model\ProductWarehouse;
use addons\kuerp\model\Staff;
use addons\kuerp\model\ExamineRecord as ExamineRecordModel;
use addons\kuerp\model\Order;
use addons\kuerp\model\PartsStock;
use addons\kuerp\model\Quote;
use addons\kuerp\model\Consume;
use addons\kuerp\model\AchievementRecords;
use addons\kuerp\model\PartsStockReload;
use addons\kuerp\model\Contract;
use addons\kuerp\model\Receivables;
use addons\kuerp\model\Approval;
use addons\kuerp\model\CustomerProduct;
use addons\kuerp\model\Customer;
use addons\kuerp\model\Achievement;
use addons\kuerp\model\Delivery;
use addons\kuerp\model\Instock;
use addons\kuerp\model\Outstock;
use addons\kuerp\model\Leave;
use addons\kuerp\model\AttendanceCard;
use addons\kuerp\model\GoodsSales;
use addons\kuerp\model\Admin;
use addons\kuerp\model\Commonseal;
use addons\kuerp\model\Expense;
use addons\kuerp\model\ScoreApply as ModelScoreApply;
use addons\kuerp\model\StaffMember;
use app\admin\model\department\Admin as AdminDepartment;
use app\admin\model\ScoreApply;
use think\Db;
use think\Exception;
use think\Log;
/**
 * 审批记录
 */
class ExamineRecord extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];
    protected $examine_index = 0;
    protected $last_examine_indexs = [];//获取审批流程中当前用户可审核的级数 0开始
    protected $children_ids = [];//当前用户直属下级人员
    protected $first_children_ids = [];//当前用户直属下级人员
    protected $flows = [];

    public function _initialize()
    {
        parent::_initialize();
        $type = input("type") ?? input('relation_type');
        $relation_type = Flows::GOODSSALE_STATUS;
        if ($type == 'expense') {
            $relation_type = Flows::EXPENSE_STATUS;
        }elseif ($type == 'contract' || $type == 'goodssale') {
            $relation_type = Flows::GOODSSALE_STATUS;
        }elseif ($type == 'score') {
            $relation_type = Flows::SCORE_STATUS;
        }elseif ($type == 'common_seal') {
            $relation_type = Flows::COMMON_SEAL;
        }
        //获取审批流程
        $flows = Flows::where(['relation_type' => $relation_type, 'status' => 1])->find();
        if (empty($flows)){
            $this->error('请先设置并启用审批流程');
        }
        $flows['flow_items'] = json_decode($flows['flow_items'], true);
        //判断流程中是否有当前用户审核
        $examine_index = 0;
        foreach ($flows['flow_items'] as $key => $value) {
            if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                $examine_index = $key + 1;
                $this->last_examine_indexs[] = $key;
                // break;
            }
        }
        if ($examine_index == 0) {
            $this->error('您不在审批流程中');
        }
        //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
        $search_index = array_search(0, $this->last_examine_indexs);
        if(count($this->last_examine_indexs) > 1 && $search_index !== false) {
            //获取直属下级
            $department_ids = AdminDepartment::getPrincipalIds($this->auth->id);
            if ($department_ids) {
                $children_ids = AdminDepartment::getDepartmentAdminIds($department_ids, true);
                //系统设置特定审核人员
                $config_examine_admins = config('site.examine_admins');
                $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                $this->children_ids = $children_ids;
                if ($children_ids) {
                    $this->first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                }
            }
            $this->last_examine_indexs = array_values(array_diff($this->last_examine_indexs, [0]));
        }
        $this->examine_index = $examine_index;
        $this->flows = $flows;
    }
    //审批记录
    public function getList()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');

        $list = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => $relation_id,
        ])->with('checkStaff')->select();
        $list = collection($list)->toArray();


        $this->success('请求成功', $list);
    }

    //审核
    public function examine()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');
        $remark = input('content', '');
        $status = input('status');//1通过 2拒绝
        $status = $status == 1 ? 1 : 0;
        if (!$status) {
            if (empty($remark)) {
                $this->error('请填写审批不通过原因');
            }
        }
        $model = new ExamineRecordModel();
        $type = '';
        switch ($relation_type) {
            case $model::CONTRACT_TYPE://合同
                $type = 'goods_sale';
                $rowModel = new GoodsSales();
                $row = $rowModel->where(['id' => $relation_id])->find();
                if (empty($row)) {
                    $this->error('数据不存在');
                }
                $log = [
                    'flows_id' => $this->flows['id'],
                    'relation_type' => $type,
                    'relation_id' => $row['id'],
                    'cur_index' => $this->examine_index,
                    'admin_id' => $this->auth->id,
                    'examine_status' => $status,
                    'remark' => $remark,
                    'createtime' => time(),
                ];
                $update = [
                    'examine_status' => $status ? 0 : 2,
                    'examine_time' => time(),
                    'examine_remark' => $remark,
                    'examine_id' => $this->auth->id,
                    'examine_index' => $status ? $this->examine_index : 0,//审核拒绝回到最开始
                    'examine_adminids' => '',//
                ];
                //判断这一级审批类型 stafftype=1 任意一人审批； stafftype=2 多人会签
                $flow_item = $this->flows['flow_items'][$this->examine_index - 1] ?? [];
                if ($status && !empty($flow_item['stafftype']) && $flow_item['stafftype'] == 2) {
                    //查看其他人是否已审核
                    if ($flow_item['admin_id'] != (string)$this->auth->id) {
                        //这一级需要审核的人员
                        $admin_ids = explode(',', $flow_item['admin_id']);
                        //这一级已审核的人员
                        $sale_adminids = $row['examine_index'] == $this->examine_index && $row['examine_adminids'] ? explode(',', $row['examine_adminids']) : [];
                        $sale_adminids[] = $this->auth->id;
                        $sale_adminids = array_intersect($admin_ids,$sale_adminids);
                        if (count($sale_adminids) < count($admin_ids)) {
                            unset($update['examine_index']); 
                            $update['examine_adminids'] = $row['examine_adminids'] ? $row['examine_adminids'] . ',' . $this->auth->id : $this->auth->id;
                        }
                    }
                }
                $update['check_history_uids'] = $row['check_history_uids'] ? $row['check_history_uids'] . ',' . $this->auth->id : $this->auth->id;
                $update['check_history_uids'] = $status ? $update['check_history_uids'] : '';//拒绝清空已审批人
                //最后一级审批需要前面有人审批
                if ($status && !empty($update['examine_index']) && $this->examine_index == count($this->flows['flow_items']) && $row['examine_index'] == 0) {
                    $this->error('很抱歉，前面的人员还没有审批');
                }
                $result = false;
                Db::startTrans();
                try {
                    $logid = Db::name('examine_log')->insertGetId($log);
                    
                    $result = $rowModel->where(['id'=>$relation_id])->update($update);
                    if ($result !== false) {
                        //判断是否审批最后一级
                        if ($status && !empty($update['examine_index']) && $this->examine_index == count($this->flows['flow_items'])) {
                            $res = $this->examinesave($row['id'], 1);
                            if ($res['status'] == 0) {
                                throw new Exception($res['msg']);
                            }

                            //同步续费网络锁、材价会员、询价条数
                            $goodsale_info = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->select();
                            foreach ($goodsale_info as $k=>$v){
                                if(in_array($v['goods_code'],array_merge($this->goods_code_caijia,$this->goods_code_xunjia))){  //判断是否有材价通账号
                                    if(empty($v['remark'])){
                                        throw new Exception('商品'.$v['goods_code'].'{备注栏}材价通手机号不存在');
                                    }
                                    if(empty($v['goods_number']) && in_array($v['goods_code'],$this->goods_code_xunjia)){
                                        throw new Exception('商品'.$v['goods_code'].'未输入续费询价条数');
                                    }
                                    if(empty($v['year_number']) && in_array($v['goods_code'],$this->goods_code_caijia)){
                                        throw new Exception('商品'.$v['goods_code'].'未输入续费时长');
                                    }
                                    if(!empty($v['remark'])){
                                        $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$v['remark']));
                                    }
                                    $user_caijia = [];
                                    $caijiaUserModel = new \app\common\model\caijiatong\User();
                                    foreach ($remark as $remark_mobile){
                                        $caijia_user = $caijiaUserModel->getUserInfo($remark_mobile);
                                        $user_caijia[] = $caijia_user;
                                        if(!$caijia_user){
                                            throw new Exception('材价通会员账号'.$remark_mobile.'不存在');
                                        }
                                    }

                                    $num = in_array($v['goods_code'],$this->goods_code_xunjia) ? $v['goods_number'] : $v['year_number'];
                                    $type = in_array($v['goods_code'],$this->goods_code_xunjia) ? 2 : 1;
                                    //续费材价会员，询价条数
                                    \app\admin\model\kuerp\GoodsSales::updatecaijia($user_caijia,$num,$type,['purchase_code'=>$row['purchase_code'],'sale_user_name'=>$row['sale_user_name']]);
                                }
                                if(in_array($v['goods_code'],$this->goods_code_wls)){  //判断网络锁是否存在
                                    if(empty($v['remark'])){
                                        throw new Exception('商品'.$v['goods_code'].'{备注栏}网络锁锁内码不存在');
                                    }
                                    if(empty($v['year_number'])){
                                        throw new Exception('商品'.$v['goods_code'].'未输入续费时长');
                                    }
                                    if(!empty($v['remark'])){
                                        $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$v['remark']));
                                    }
                                    $user_caijia = [];
                                    $caijiaUserSoftwareModel = new \app\common\model\caijiatong\UserSoftware();
                                    foreach ($remark as $remark_mobile){
                                        if (((string)$remark_mobile)[0] != '2' && substr((string)$remark_mobile, 0, 5) != 'NBGV0') {
                                            $this->error($remark_mobile.'不是网络锁');
                                        }
                                        $caijia_user = $caijiaUserSoftwareModel->getUsersoftwareInfo($remark_mobile);
                                        $user_caijia[] = $caijia_user;
                                        if(!$caijia_user){
                                            throw new Exception('网络锁'.$remark_mobile.'不存在');
                                        }
                                    }

                                    //续费材价会员，询价条数
                                    \app\admin\model\kuerp\GoodsSales::updatecaijia($user_caijia,$v['year_number'],3,['purchase_code'=>$row['purchase_code'],'sale_user_name'=>$row['sale_user_name'],'goods_code'=>$v['goods_code']]);
                                }
                            }

                            Message::addMessage(Message::EXAMINE_ADOPT_TYPE, $logid, $row['preparation_id'], $this->auth->id);
                        }
                    }
                    if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $relation_id, 'to_staff_id' => $this->auth->id])->find()) {
                        Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
                    }
                    if ($status) {
                        $flow = Flows::getFlowByTypes($relation_type);
                        //给下一审核人发送通知
                        $check_staff_ids = $update['check_history_uids'];
                        $result = Flows::sendStepRecord($flow, $relation_type, $relation_id, $check_staff_ids, $update['examine_index'] ?? $row['examine_index']);
                    } else {
                        Message::addMessage(Message::EXAMINE_REFUSE_TYPE, $logid, $row['preparation_id'], $this->auth->id, '');
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                break;
            case $model::EXPENSE_TYPE://报销
                $type = 'expense';
                $rowModel = new Expense();
                $row = $rowModel->where(['id' => $relation_id])->find();
                if (empty($row)) {
                    $this->error('数据不存在');
                }
                $log = [
                    'flows_id' => $this->flows['id'],
                    'relation_type' => $type,
                    'relation_id' => $row['id'],
                    'cur_index' => $this->examine_index,
                    'admin_id' => $this->auth->id,
                    'examine_status' => $status,
                    'remark' => $remark,
                    'createtime' => time(),
                ];
                $update = [
                    'check_status' => $status ? $row['check_status'] : 3,
                    'check_remark' => $remark,
                    'check_last_uid' => $this->auth->id,
                    'check_step_sort' => $status ? $this->examine_index : 0,//审核拒绝回到最开始
                    'check_uids' => '',//
                ];
                //判断这一级审批类型 stafftype=1 任意一人审批； stafftype=2 多人会签
                $flow_item = $this->flows['flow_items'][$this->examine_index - 1] ?? [];
                if ($status && !empty($flow_item['stafftype']) && $flow_item['stafftype'] == 2) {
                    //查看其他人是否已审核
                    if ($flow_item['admin_id'] != (string)$this->auth->id) {
                        //这一级需要审核的人员
                        $admin_ids = explode(',', $flow_item['admin_id']);
                        //这一级已审核的人员
                        $sale_adminids = $row['check_step_sort'] == $this->examine_index && $row['check_uids'] ? explode(',', $row['check_uids']) : [];
                        $sale_adminids[] = $this->auth->id;
                        $sale_adminids = array_intersect($admin_ids,$sale_adminids);
                        if (count($sale_adminids) < count($admin_ids)) {
                            unset($update['check_step_sort']); 
                            $update['check_uids'] = $row['check_uids'] ? $row['check_uids'] . ',' . $this->auth->id : $this->auth->id;
                        }
                    }
                }
                //如果申请人本身在审批人员中，判断退回到该申请人所在审批步骤
                if (!$status) {
                    $examine_index = 0;
                    foreach ($this->flows['flow_items'] as $key => $value) {
                        if (in_array($row['admin_id'], explode(',',$value['admin_id'])) ) {
                            $examine_index = $key + 1;
                            // break;
                        }
                    }
                    $update['check_step_sort'] = $examine_index;
                }
                $update['check_history_uids'] = $row['check_history_uids'] ? $row['check_history_uids'] . ',' . $this->auth->id : $this->auth->id;
                $update['check_history_uids'] = $status ? $update['check_history_uids'] : '';//拒绝清空已审批人
                //最后一级审批
                if (!empty($update['check_step_sort']) && $this->examine_index == count($this->flows['flow_items'])){
                    $update['check_status'] = 2;
                    $update['check_time'] = time();
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $logid = Db::name('examine_log')->insertGetId($log);
                    
                    $result = $rowModel->where(['id'=>$relation_id])->update($update);
                    if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $relation_id, 'to_staff_id' => $this->auth->id])->find()) {
                        Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
                    }
                    if ($status) {
                        $flow = Flows::getFlowByTypes($relation_type);
                        //给下一审核人发送通知
                        $check_staff_ids = $update['check_history_uids'];
                        $result = Flows::sendStepRecord($flow, $relation_type, $relation_id, $check_staff_ids, $update['check_step_sort'] ?? $row['check_step_sort']);
                        //完成审批发送
                        if ($update['check_status'] == 2) {
                            Message::addMessage(Message::EXAMINE_ADOPT_TYPE, $logid, $row['admin_id'], $this->auth->id);
                        }
                    } else {
                        Message::addMessage(Message::EXAMINE_REFUSE_TYPE, $logid, $row['admin_id'], $this->auth->id, '');
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                break;
            case $model::SCORE_TYPE://积分申请
                $type = 'score';
                $rowModel = new ScoreApply();
                $row = $rowModel->where(['id' => $relation_id])->find();
                if (empty($row)) {
                    $this->error('数据不存在');
                }
                $log = [
                    'flows_id' => $this->flows['id'],
                    'relation_type' => $type,
                    'relation_id' => $row['id'],
                    'cur_index' => $this->examine_index,
                    'admin_id' => $this->auth->id,
                    'examine_status' => $status,
                    'remark' => $remark,
                    'createtime' => time(),
                ];
                $update = [
                    'check_status' => $status ? $row['check_status'] : 3,
                    'check_remark' => $remark,
                    'check_last_uid' => $this->auth->id,
                    'check_step_sort' => $status ? $this->examine_index : 0,//审核拒绝回到最开始
                    'check_uids' => '',//
                ];
                //判断这一级审批类型 stafftype=1 任意一人审批； stafftype=2 多人会签
                $flow_item = $this->flows['flow_items'][$this->examine_index - 1] ?? [];
                if ($status && !empty($flow_item['stafftype']) && $flow_item['stafftype'] == 2) {
                    //查看其他人是否已审核
                    if ($flow_item['admin_id'] != (string)$this->auth->id) {
                        //这一级需要审核的人员
                        $admin_ids = explode(',', $flow_item['admin_id']);
                        //这一级已审核的人员
                        $sale_adminids = $row['check_step_sort'] == $this->examine_index && $row['check_uids'] ? explode(',', $row['check_uids']) : [];
                        $sale_adminids[] = $this->auth->id;
                        $sale_adminids = array_intersect($admin_ids,$sale_adminids);
                        if (count($sale_adminids) < count($admin_ids)) {
                            unset($update['check_step_sort']); 
                            $update['check_uids'] = $row['check_uids'] ? $row['check_uids'] . ',' . $this->auth->id : $this->auth->id;
                        }
                    }
                }
                //如果申请人本身在审批人员中，判断退回到该申请人所在审批步骤
                if (!$status) {
                    $examine_index = 0;
                    foreach ($this->flows['flow_items'] as $key => $value) {
                        if (in_array($row['admin_id'], explode(',',$value['admin_id'])) ) {
                            $examine_index = $key + 1;
                            // break;
                        }
                    }
                    $update['check_step_sort'] = $examine_index;
                }
                $update['check_history_uids'] = $row['check_history_uids'] ? $row['check_history_uids'] . ',' . $this->auth->id : $this->auth->id;
                $update['check_history_uids'] = $status ? $update['check_history_uids'] : '';//拒绝清空已审批人
                //最后一级审批
                if ($status && !empty($update['check_step_sort']) && $this->examine_index == count($this->flows['flow_items'])){
                    $update['check_status'] = 2;
                    $update['check_time'] = time();
                    $update['pay_status'] = 1;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $logid = Db::name('examine_log')->insertGetId($log);
                    
                    $result = $rowModel->where(['id'=>$relation_id])->update($update);
                    if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $relation_id, 'to_staff_id' => $this->auth->id])->find()) {
                        Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
                    }
                    if ($status) {
                        $flow = Flows::getFlowByTypes($relation_type);
                        //给下一审核人发送通知
                        $check_staff_ids = $update['check_history_uids'];
                        $result = Flows::sendStepRecord($flow, $relation_type, $relation_id, $check_staff_ids, $update['check_step_sort'] ?? $row['check_step_sort']);
                        //完成审批发送
                        if ($update['check_status'] == 2) {
                            Message::addMessage(Message::EXAMINE_ADOPT_TYPE, $logid, $row['admin_id'], $this->auth->id);
                            $apply_data = json_decode($row['apply_data'],true);
                            if (!empty($apply_data)) {
                                foreach ($apply_data as $apply_row){
                                    $score = $apply_row['score'] + ($apply_row['addscore'] ?? 0);
                                    \app\common\model\caijiatong\User::score($score, $apply_row['mobile'], 'CRM积分申请通过获得', 6);
                                }
                            }
                        }
                    } else {
                        Message::addMessage(Message::EXAMINE_REFUSE_TYPE, $logid, $row['admin_id'], $this->auth->id, '');
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                break;
            case $model::COMMONSEAL_TYPE://公章申请
                    $type = 'common_seal';
                    $rowModel = new Commonseal();
                    $row = $rowModel->where(['id' => $relation_id])->find();
                    if (empty($row)) {
                        $this->error('数据不存在');
                    }
                    $log = [
                        'flows_id' => $this->flows['id'],
                        'relation_type' => $type,
                        'relation_id' => $row['id'],
                        'cur_index' => $this->examine_index,
                        'admin_id' => $this->auth->id,
                        'examine_status' => $status,
                        'remark' => $remark,
                        'createtime' => time(),
                    ];
                    $update = [
                        'check_status' => $status ? $row['check_status'] : 3,
                        'check_remark' => $remark,
                        'check_last_uid' => $this->auth->id,
                        'check_step_sort' => $status ? $this->examine_index : 0,//审核拒绝回到最开始
                        'check_uids' => '',//
                    ];
                    //判断这一级审批类型 stafftype=1 任意一人审批； stafftype=2 多人会签
                    $flow_item = $this->flows['flow_items'][$this->examine_index - 1] ?? [];
                    if ($status && !empty($flow_item['stafftype']) && $flow_item['stafftype'] == 2) {
                        //查看其他人是否已审核
                        if ($flow_item['admin_id'] != (string)$this->auth->id) {
                            //这一级需要审核的人员
                            $admin_ids = explode(',', $flow_item['admin_id']);
                            //这一级已审核的人员
                            $sale_adminids = $row['check_step_sort'] == $this->examine_index && $row['check_uids'] ? explode(',', $row['check_uids']) : [];
                            $sale_adminids[] = $this->auth->id;
                            $sale_adminids = array_intersect($admin_ids,$sale_adminids);
                            if (count($sale_adminids) < count($admin_ids)) {
                                unset($update['check_step_sort']); 
                                $update['check_uids'] = $row['check_uids'] ? $row['check_uids'] . ',' . $this->auth->id : $this->auth->id;
                            }
                        }
                    }
                    //如果申请人本身在审批人员中，判断退回到该申请人所在审批步骤
                    if (!$status) {
                        $examine_index = 0;
                        foreach ($this->flows['flow_items'] as $key => $value) {
                            if (in_array($row['admin_id'], explode(',',$value['admin_id'])) ) {
                                $examine_index = $key + 1;
                                // break;
                            }
                        }
                        $update['check_step_sort'] = $examine_index;
                    }
                    $update['check_history_uids'] = $row['check_history_uids'] ? $row['check_history_uids'] . ',' . $this->auth->id : $this->auth->id;
                    $update['check_history_uids'] = $status ? $update['check_history_uids'] : '';//拒绝清空已审批人
                    //最后一级审批
                    if ($status && !empty($update['check_step_sort']) && $this->examine_index == count($this->flows['flow_items'])){
                        $update['check_status'] = 2;
                        $update['check_time'] = time();
                    }
                    
                    $result = false;
                    Db::startTrans();
                    try {
                        $logid = Db::name('examine_log')->insertGetId($log);
                        
                        $result = $rowModel->where(['id'=>$relation_id])->update($update);
                        if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $relation_id, 'to_staff_id' => $this->auth->id])->find()) {
                            Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
                        }
                        if ($status) {
                            $flow = Flows::getFlowByTypes($relation_type);
                            //给下一审核人发送通知
                            $check_staff_ids = $update['check_history_uids'];
                            $result = Flows::sendStepRecord($flow, $relation_type, $relation_id, $check_staff_ids, $update['check_step_sort'] ?? $row['check_step_sort']);
                            //完成审批发送
                            if ($update['check_status'] == 2) {
                                Message::addMessage(Message::EXAMINE_ADOPT_TYPE, $logid, $row['admin_id'], $this->auth->id);
                            }
                        } else {
                            Message::addMessage(Message::EXAMINE_REFUSE_TYPE, $logid, $row['admin_id'], $this->auth->id, '');
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    break;
                
            default:
                throw new Exception('参数错误');
        }
        

        
        if ($result !== false) {
            $this->success('审核成功');
        } else {
            $this->error('审核失败');
        }

    }

    //审核/反审核
    public function examinesave($ids = null,$examine=1){
        $rowModel = new GoodsSales();
        if($examine==1){
            $list = $rowModel->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
            if (empty($list)) {
                return ['status'=>0,'msg'=>'请选择需要审核的数据'];
            }
            $set_discount = \think\Db::name('kuerp_sets')->where(['name'=>'discount'])->value('is_checked');

            $purchase_code = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['check_status']==1){
                    // $this->error('不能反审核已对单的数据');
                    return ['status'=>0,'msg'=>'不能反审核已对单的数据'];
                }
                $purchase_code[] = $list_v['purchase_code'];
            }
            $account_list_obj = Db::name('kuerp_accounts')->field('id,account_coding,account_name,balance')->select();
            $account_list = [];
            foreach ($account_list_obj as $account_list_obj_k=>$account_list_obj_v){
                $account_list[$account_list_obj_v['id']] = $account_list_obj_v;
            }
            $examine_ids = [];
            $accountData = [];
            $arrears = [];
            $log = [];
            $payment_log = [];$invoicing = [];
            foreach ($list as $list_k=>$list_v){
                $examine_ids[] = $list_v['id'];
                if($list_v['arrears']>0){
                    $suppliers = Db::name('kuerp_customers')->where(['id'=>$list_v['customers_id']])->field('id,need_receive_account')->find();
                    if($suppliers){
                        $status = false;
                        foreach ($arrears as $arrears_k=>$arrears_v){
                            if($arrears_v['id']==$suppliers['id']){
                                $arrears[$arrears_k]['need_receive_account'] = $list_v['arrears']+$arrears_v['need_receive_account'];
                                $status = true;
                            }
                        }
                        if(!$status){
                            $arrears[] = [
                                'id'  => $suppliers['id'],
                                'need_receive_account'  => $list_v['arrears']+$suppliers['need_receive_account'],
                            ];
                        }
                    }
                }
                if($list_v['pay_money']>0){
                    $accountData[] = [
                        'balance'  => $list_v['pay_money'],
                        'account'  => $list_v['account'],
                    ];
                    $log[] = [
                        'account_coding'    => $account_list[$list_v['account']]['account_coding'],
                        'account_name'      => $account_list[$list_v['account']]['account_name'],
                        'balance'           => $account_list[$list_v['account']]['balance']-$list_v['pay_money'],
                        'income'            => $list_v['pay_money'],
                        'pay_time'          => $list_v['purchase_time'],
                        'bill_code'         => $list_v['purchase_code'],
                        'business_type'     => 5,
                        'customers_id'      => $list_v['customers_id'],
                        'remark'            => $list_v['note'],
                        'createtime'        => time(),
                        'updatetime'        => time(),
                    ];
                }
                $payment_log[] = [
                    'customers_id'   => $list_v['customers_id'],
                    'sale_user'      => $list_v['sale_user'],
                    'sale_user_name' => $list_v['sale_user_name'] ?? '',
                    'business_type'  => 1,
                    'bill_time'      => $list_v['purchase_time'],
                    'bill_code'      => $list_v['purchase_code'],
                    'bill_codes'     => $list_v['purchase_code'],
                    'purchase_money' => $list_v['all_money'],
                    'discount_money' => $list_v['preferential_money'],
                    'real_money'     => $list_v['real_money'],
                    'money_tax_price'=> $list_v['money_tax_price'],
                    'pay_money'      => $list_v['pay_money'],
                    'give_money'     => $list_v['arrears'],
                    'reamrk'         => $list_v['note'],
                    'createtime'     => time(),
                ];
                if($set_discount==1){
                    $money = $list_v['real_money'];
                }else{
                    $money = $list_v['money_tax_price'];
                }
                $invoicing[] = [
                    'customers_id'   => $list_v['customers_id'],
                    'status'         => $list_v['pay_status'],
                    'bill_time'      => $list_v['purchase_time'],
                    'bill_code'      => $list_v['purchase_code'],
                    'bill_codes'     => $list_v['purchase_code'],
                    'money'          => $list_v['real_money'],
                    'tax'            => $list_v['tax_money'],
                    'real_money'     => $money,
                    'pay_money'      => 0,
                    'give_money'     => $money,
                    'createtime'     => time(),
                ];
            }
            $editstock = [];$addstock = [];$goods_stock = [];
            $info_list = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->select();
            //注释20241011
            // foreach ($info_list as $info_list_k=>$info_list_v){
            //     try {
            //         unset($info_list[$info_list_k]['period']);
            //     } catch (Exception $e) {
            //     }
            // }

            $purchase_info_id = $info_list ? array_column($info_list, 'id') : [];//Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->column('id');

            $purchase_info = [];
            $goods_stock_log = [];//收发详情
            $serial_log = [];//序列号跟踪
            foreach ($info_list as $list_k=>$list_v){
                //序列号跟踪
                $goods_serial = Db::name('kuerp_goods_serial')->where(['sale_id'=>$list_v['id']])->field('goods_id,serial,stores_id,attribute_id')->select();
                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                    $serial_log[] = [
                        'admin_id' => $this->auth->id,
                        'goods_id'=>$goods_serial_v['goods_id'],
                        'stores_id'=>$goods_serial_v['stores_id'],
                        'attribute_id'=>$goods_serial_v['attribute_id'],
                        'serial'=>$goods_serial_v['serial'],
                        'business_type'=>'4',
                        'store_status'=>'2',
                        'remarks' => $list_v['remark'],
                        'purchase_id'=>$list_v['id'],
                        'customer_id'=>$list_v['customers_id'],
                        'purchase_code'=>$list_v['purchase_code'],
                        'purchase_time' => $list_v['purchase_time'],
                        'createtime'  => time(),
                        'updatetime'  => time(),
                    ];
                }
                //序列号跟踪

                $info_list[$list_k]['sales_order_id']    = $list_v['id'];
                $info_list[$list_k]['createtime']        = time();
                $info_list[$list_k]['updatetime']        = time();
                $stock_number = $list_v['basic_nmber'];
                //判断该商品是否启用序列号 且该订单是否有序列号
                $goods = Db::name('kuerp_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id,serial')->find();
                if($goods['serial']==1){
                    $stock_number = count($goods_serial);
                }
                $status = false;
                foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                    if($goods_stock_v['id']==$goods['id']){
                        $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']-$stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $goods_stock[] = [
                        'id'=>$goods['id'],
                        'inventory'=>$goods['inventory']-$stock_number,
                    ];
                }
                //商品库存
                $where = [];
                $where['goods_code'] = $list_v['goods_code'];
                $where['stores_id'] = $list_v['stores_id'];
                if($list_v['goods_attr']>0){
                    $goods_attr = $list_v['goods_attr'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                }

                //获取成本单价
                $balance_cost=0;$balance_unit=0;
                $goodsInfo = json_decode((new Goods())->getUnit($list_v['goods_code'],$list_v['stores_id'],$list_v['goods_attr']),true);
                $unitData = isset($goodsInfo['unit'])?$goodsInfo['unit']:[];
                if(empty($unitData)){
                    return ['status'=>0,'msg'=>'商品信息获取错误'];
                }else{
                    foreach ($unitData as $unitData_k=>$unitData_v){
                        if($unitData_v['id']==$goods['unit_id']){
                            $balance_unit = $unitData_v['purchase'];
                        }
                    }
                }
                //获取成本单价结束

                $stock = Db::name('kuerp_goods_stock')->where($where)->field('stock,id')->find();
                if($stock){
                    $status = false;
                    foreach ($editstock as $editstock_k=>$editstock_v){
                        if($editstock_v['id']==$stock['id']){
                            $editstock[$editstock_k]['stock'] -= $stock_number;
                            $status = true;
                            $balance_cost   = (round($balance_unit*$stock_number,4));
                        }
                    }
                    if(!$status){
                        $editstock[] = [
                            'id'=>$stock['id'],
                            'stock'=>(round($stock['stock']-$stock_number,4))
                        ];
                        $balance_cost   = (round($balance_unit*$stock_number,4));
                    }
                }else{
                    //判断是否启用序列号 启用了才需要库存 是否选择了序列号
                    if($goods['serial']==1 && count($goods_serial)){
                        $store = Db::name('kuerp_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                        return ['status'=>0,'msg'=>'商品'.$store.'库存不足'];
                    }
                }
                $purchase_info[] = $list_v['id'];

                //收发详情
                if($goods){
                    $goods_stock_log[] = [
                        'admin_id'      => $this->auth->id,
                        'purchase_code' => $list_v['purchase_code'],
                        'purchase_id'   => $list_v['id'],
                        'purchase_time' => $list_v['purchase_time'],
                        'business_type' => '4',
                        'customer_id'   => $list_v['customers_id'],
                        'goods_id'      => $goods['id'],
                        'goods_code'    => $list_v['goods_code'],
                        'attribute_id'  => (float)$list_v['goods_attr'],
                        'goods_unit'    => (float)$list_v['goods_unit'],
                        'stores_id'     => (float)$list_v['stores_id'],
                        'remark'        => $list_v['remark'],
                        'out_number'    => (float)$list_v['number'],
                        'out_basics'    => (float)$list_v['basic_nmber'],
                        'out_unit'      => $balance_unit,
                        'out_cost'      => $balance_cost,
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ];
                }
                //收发详情结束
            }
            foreach ($editstock as $editstock_k=>$editstock_v){
                if($editstock_v['stock']<0){
                    $store = Db::name('kuerp_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                    // if($examine_set!=1){
                    //     return ['status'=>0,'msg'=>$goods['goods_name'].'库存不足,操作失败'];
                    // }
                    return ['status'=>0,'msg'=>$store.$goods['goods_name'].'库存不足,操作失败'];
                    // $this->error($store.'库存不足,操作失败');
                }
            }

            $order_count = [];
            $code_id = Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->column('order_id');
            $purchase_order_info = Db::name('kuerp_goods_sales_order_info')
                ->field('id,purchase_code')
                ->where(['id'=>['in',$code_id]])
                ->select();
            foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
                $purord_info = Db::name('kuerp_goods_saleord_info')
                    ->where(['order_id'=>$purchase_order_info_v['id'],'purchase_id'=>['in',$purchase_info]])->field('sum(number) as number,sum(money) as money,sum(all_money) as all_money')->find();
                $purchase_order_info[$purchase_order_info_k]['pay_count'] = isset($purord_info['number'])?$purord_info['number']:0;
                $purchase_order_info[$purchase_order_info_k]['pay_money'] = isset($purord_info['money'])?$purord_info['money']:0;
                $purchase_order_info[$purchase_order_info_k]['all_money'] = isset($purord_info['all_money'])?$purord_info['all_money']:0;
            }
            foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
                $status = false;
                foreach ($order_count as $order_count_k=>$order_count_v){
                    if($order_count_v['purchase_code']==$purchase_order_info_v['purchase_code']){
                        $order_count[$order_count_k]['store_number'] += $purchase_order_info_v['pay_count'];
                        $status = true;
                    }
                }
                if(!$status){
                    $order_count[] = [
                        'purchase_code'  => $purchase_order_info_v['purchase_code'],
                        'store_number'  => $purchase_order_info_v['pay_count'],
                    ];
                }
            }
            //修改状态
            if(!empty($order_count)){
                foreach ($order_count as $order_count_k=>$order_count_v){
                    $number = Db::name('kuerp_goods_sales_order')->where(['purchase_code'=>$order_count_v['purchase_code']])->field('id,number,store_number')->find();
                    if(($number['number']-$number['store_number'])<=$order_count_v['store_number']){
                        $order_count[$order_count_k]['status'] = 1;
                    }else{
                        $order_count[$order_count_k]['status'] = 2;
                    }
                    $order_count[$order_count_k]['id'] = $number['id'];
                }
            }

            //批次库存数据
            //获取设置
            $set= \think\Db::name('kuerp_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $number_decimal = $setList['number_decimal']['value'];
            $goods_serial = Db::name('kuerp_goods_sales_info')->where(['id'=>['in',$purchase_info_id]])->select();

            $goods_batch_add = [];$goods_batch_edit = [];$goods_batch_log = [];
            foreach ($goods_serial as $k=>$v){
                $goods = Db::name('kuerp_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
                if($goods['batch']==1){
                    //先通过单位计算需修改多单位商品的库存数量
                    if($goods['unit_id']==$v['goods_unit']){
                        $stock_number = $v['number'];
                    }else{
                        $unit_conversion = Db::name('kuerp_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']])->value('advance_rate');
                        if(empty($unit_conversion)){
                            // if($examine_set!=1){
                            //     return ['status'=>0,'msg'=>'商品单位信息查询失败'];
                            // }
                            // $this->error('商品单位信息查询失败');
                            return ['status'=>0,'msg'=>'商品单位信息查询失败'];
                        }else{
                            $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                        }
                    }

                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    if($v['goods_attr']){
                        $where['attribute_id'] = $v['goods_attr'];
                    }
                    $where['stores_id'] = $v['stores_id'];
                    $where['batch_id'] = $v['batch_id'];
                    $goods_batch_stock = Db::name('kuerp_goods_batch_stock')->where($where)->find();
                    if(empty($goods_batch_stock)){
                        $status = false;
                        foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                            if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$v['goods_id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                                $goods_batch_add[$goods_batch_add_k]['stock'] -= $stock_number;
                                $status = true;
                            }
                        }
                        if(!$status){
                            $goods_batch_add[] = [
                                'admin_id' => $this->auth->id,
                                'batch_id' => $v['batch_id'],
                                'goods_id' => $goods['id'],
                                'goods_code' => $v['goods_code'],
                                'attribute_id' => $v['goods_attr'],
                                'stores_id' => $v['stores_id'],
                                'stock' => $stock_number,
                                'createtime' => time(),
                                'updatetime' => time(),
                            ];
                        }
                    }else{
                        if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                            $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                        }else{
                            $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                        }
                    }
                    foreach ($goods_batch_edit as $k2=>$v2){
                        if($v2<0){
                            // if($examine_set!=1){
                            //     return ['status'=>0,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                            // }
                            // $this->error('商品'.$goods['goods_name'].'库存不足');
                            return ['status'=>0,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                        }
                    }

                    //商品批次跟踪
                    $goods_batch_log[] = [
                        'admin_id'      => $this->auth->id,
                        'goods_id'      => $goods['id'],
                        'goods_unit'    => $v['goods_unit'],
                        'stores_id'     => $v['stores_id'],
                        'batch_id'      => (float)$v['batch_id'],
                        'number'        => (float)$v['number'],
                        'purchase_code' => $v['purchase_code'],
                        'purchase_time' => $v['purchase_time'],
                        'business_type' => '4',
                        'remarks'       => $v['remark'],
                        'order_id'      => $v['id'],
                        'unit_price'    => $v['unit_price'],
                        'tax_included'  => $v['tax_included'],
                        'all_money'     => $v['all_money'],
                        'tax_money'     => $v['tax_money'],
                        'money_tax_price' => $v['money_tax_price'],
                        'customer_id'   => $v['customers_id'],
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ];
                }
                //商品批次跟踪结束
            }
            //批次库存数据结束

            //应收账款明细表
            $ex_list = $rowModel->where(['id'=>['in',$ids],'examine_status'=>'0','arrears'=>['>','0']])->select();
            $accounts_receivable = [];
            foreach ($ex_list as $ex_list_k=>$ex_list_v){
                $accounts_receivable[] = [
                    'admin_id'          => $this->auth->id,
                    'customers_id'      => $ex_list_v['customers_id'],
                    'purchase_time'     => $ex_list_v['purchase_time'],
                    'purchase_code'     => $ex_list_v['purchase_code'],
                    'business_type'     => '6',
                    'receivable'        => $ex_list_v['arrears'],
                    'staff_member_id'   => $ex_list_v['sale_user'],
                    'sale_user_name'    => $ex_list_v['sale_user_name'] ?? '',
                    'remark'            => $ex_list_v['note'],
                    'sale_money'        => $ex_list_v['money_tax_price'],
                    'receivable_money'  => round(($ex_list_v['real_money']+$ex_list_v['customers_money']),4),
                    'amount'            => $ex_list_v['preferential_money'],
                    'cost'              => $ex_list_v['customers_money'],
                    'real_money'        => $ex_list_v['pay_money'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ];
            }

            $admin = Admin::info();

            //采购销售费用
            $cost_data = [];
            foreach ($list as $list_k=>$list_v){
                if(!empty($list_v['cost_data'])){
                    $cost_datas = unserialize($list_v['cost_data']);
                    foreach ($cost_datas as $cost_datas_k=>$cost_datas_v){
                        $list_v['supplyer_code'] = isset($list_v['supplyer_code'])?$list_v['supplyer_code']:'';
                        $cost_data[] = [
                            'admin_id'          => $this->auth->id,
                            'purchase_time'     => time(),
                            'purchase_code'     => (new Goods())->getCodes('',27),
                            'business_type'     => '2',
                            'suppliers_ids'     => isset($list_v['customers_id'])?$list_v['customers_id']:null,
                            'suppliers_id'      => $cost_datas_v['suppliers_id'],
                            'expend_type_id'    => $cost_datas_v['expend_type_id'],
                            'purchase_number'   => $list_v['purchase_code'],
                            'purchase_times'    => $list_v['purchase_time'],
                            'money'             => $cost_datas_v['money'],
                            'pay_money'         => $cost_datas_v['money'],
                            'remark'            => $cost_datas_v['remark'],
                            'preparation_id'    => $this->auth->id,
                            'operation_id'      => $this->auth->id,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }
                }
            }

            //销售利润表
            $profit = [];
            foreach ($list as $list_k=>$list_v){
                $amount = null;
                $amounts = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$list_v['purchase_code']])->sum('dis_money');
                if($amounts>0){
                    $amount = $amounts;
                }

                $profit[] = [
                    'admin_id'      => $this->auth->id,
                    'purchase_type' => '1',
                    'purchase_code' => $list_v['purchase_code'],
                    'purchase_time' => $list_v['purchase_time'],
                    'customers_id'  => $list_v['customers_id'],
                    'sale_user'     => $list_v['sale_user'],
                    'sale_user_name'=> $list_v['sale_user_name'] ?? '',
                    'preparation_id'=> $list_v['preparation_id'],
                    'examine_id'    => $admin->id,
                    'number'        => $list_v['number'],
                    'amount'        => $amount,
                    'all_money'     => $list_v['all_money'],
                    'tax_money'     => $list_v['tax_money'],
                    'money_tax_price'=> $list_v['money_tax_price'],
                    'preferential_money'=> $list_v['preferential_money'],
                    'purchase_money'=> $list_v['purchase_money'],
                    'real_money'    => $list_v['real_money'],
                    'customers_money'=> $list_v['customers_money'],
                    'need_money'    => $list_v['real_money']+$list_v['customers_money'],
                    'pay_money'     => $list_v['pay_money'],
                    'remark'        => $list_v['note'],
                ];
            }

            //核销单源单
            $writeoff_source = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['arrears']>0){
                    $writeoff_source[] = [
                        'purchase_type' => 3,
                        'type' => 1,
                        'customers_id' => $list_v['customers_id'],
                        'purchase_code' => $list_v['purchase_code'],
                        'purchase_time' => $list_v['purchase_time'],
                        'price' => $list_v['real_money'],
                        'money' => $list_v['pay_money'],
                        'write_off' => $list_v['arrears'],
                        'remark' => $list_v['note'],
                    ];
                }
            }

            Db::startTrans();
            try {
                if(!empty($writeoff_source)){
                    Db::name('kuerp_writeoff_source')->insertAll($writeoff_source);
                }
                
                if(!empty($profit)){
                    Db::name('kuerp_goods_sales_profit')->insertAll($profit);
                }
                if(!empty($cost_data)){
                    Db::name('kuerp_cost')->insertAll($cost_data);
                }
                if(!empty($accounts_receivable)){
                    Db::name('kuerp_accounts_receivable')->insertAll($accounts_receivable);
                }

                //序列号跟踪
                if(!empty($serial_log)){
                    Db::name('kuerp_goods_serial_log')->insertAll($serial_log);
                }
                if(!empty($goods_stock_log)){
                    Db::name('kuerp_goods_log')->insertAll($goods_stock_log);
                }
                //批次库存数据
                if(!empty($goods_batch_log)){
                    Db::name('kuerp_goods_batch_log')->insertAll($goods_batch_log);
                }
                if(!empty($goods_batch_add)){
                    foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                        $where = [];
                        $where['goods_code'] = $goods_batch_add_v['goods_code'];
                        $where['stores_id'] = $goods_batch_add_v['stores_id'];
                        $where['batch_id'] = $goods_batch_add_v['batch_id'];
                        if($goods_batch_add_v['attribute_id']>0){
                            $where['attribute_id'] = $goods_batch_add_v['attribute_id'];
                        }
                        $stock = Db::name('kuerp_goods_batch_stock')->where($where)->find();
                        if($stock){
                            Db::name('kuerp_goods_batch_stock')->where(['id'=>$stock['id']])->inc('stock',$goods_batch_add_v['stock'])->update();
                        }else{
                            Db::name('kuerp_goods_batch_stock')->insert($goods_batch_add_v);
                        }
                    }
                }
                if(!empty($goods_batch_edit)){
                    foreach ($goods_batch_edit as $k=>$v){
                        Db::name('kuerp_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                    }
                }
                //批次库存数据结束

                if(!empty($purchase_info_id)){
                    Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_info_id]])->update(['store_status'=>'2']);
                    Db::name('kuerp_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->update(['status'=>'1']);
                }
                if(!empty($order_count)){
                    $goodsSalesOrder = (new \app\admin\model\kuerp\GoodsSalesOrder());
                    foreach ($order_count as $order_count_k=>$order_count_v){
                        $goodsSalesOrder->where(['id'=>$order_count_v['id']])->inc('store_number',$order_count_v['store_number'])->update();
                        unset($order_count[$order_count_k]['store_number']);
                    }
                    $goodsSalesOrder->saveAll($order_count);
                }
                if(!empty($payment_log)){
                    (new \app\admin\model\kuerp\SalesPaymentLog())->saveAll($payment_log);
                }
                if(!empty($invoicing)){
                    (new \app\admin\model\kuerp\SalesInvoicing())->saveAll($invoicing);
                }
                $result = $rowModel->where(['id'=>['in',$ids],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$admin->id,'examine_time'=>time(),'operation_id'=>$admin->id]);
                if(!empty($log)){
                    Db::name('kuerp_accounts_log')->insertAll($log);
                }
                if(!empty($editstock)){
                    (new \app\admin\model\kuerp\GoodsStock())->saveAll($editstock);
                }
                if(!empty($goods_stock)){
                    (new \app\admin\model\kuerp\Goods())->saveAll($goods_stock);
                }
                if(!empty($arrears)){
                    (new \app\admin\model\kuerp\Customers())->saveAll($arrears);
                }
                Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->update(['status'=>'1','times'=>time()]);
                foreach ($info_list as $info_list_k=>$info_list_v){
                    if(isset($info_list_v['id'])){
                        $info_list[$info_list_k]['salesinfoid'] = $info_list_v['id'];
                        unset($info_list[$info_list_k]['id']);
                    }
                }
                Db::name('kuerp_goods_sales_summary')->insertAll($info_list);
                if(!empty($accountData)){
                    foreach ($accountData as $accountData_k=>$accountData_v){
                        Db::name('kuerp_accounts')->where(['id'=>$accountData_v['account']])->inc('balance',$accountData_v['balance'])->update();
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                // if($examine_set!=1){
                //     return ['status'=>1,'msg'=>'操作成功'];
                // }
                // $this->success(sizeof($list).'条数据审核成功');
                return ['status'=>1,'msg'=>'操作成功'];
            }else{
                // if($examine_set!=1){
                //     return ['status'=>0,'msg'=>'操作失败'];
                // }
                // $this->error('审核失败');
                return ['status'=>0,'msg'=>'审核失败'];
            }
        }
    }

    //批量审核费用
    public function examine_consume()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');
        $content = input('content');
        $status = input('status');

        $relation_id = explode(',', $relation_id);
        if (empty($relation_id)) {
            $this->error('参数错误');
        }
        $record = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => ['in', $relation_id],
            'status' => ['neq', 0],
        ])->select();
        if (!empty($record)) {
            $this->error('有已审核数据，请刷新页面');
        }
        $saveIds = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => ['in', $relation_id],
        ])->column('id');
        $staff = Staff::info();
        Db::startTrans();
        try {
            $model = new ExamineRecordModel();
            if ($model->isUpdate(true)->save([
                    'status' => $status,
                    'content' => $content,
                    'check_time' => time()
                ], ['id' => ['in', $saveIds]]) == false) {
                throw new Exception('修改失败');
            }

            switch ($relation_type) {
                case $model::CONSUME_TYPE://费用
                    $rowModel = new Consume();
                    $row = $rowModel->where(['id' => ['in', $relation_id]])->select();
                    $row = collection($row)->toArray();
                    break;
                default:
                    throw new Exception('参数错误');
            }
            if ($message_ids = Message::where(['relation_type' => 'examine', 'relation_id' => ['in', $saveIds], 'to_staff_id' => $this->auth->id])->column('id')) {
                Message::where(['id' => ['in', $message_ids]])->update(['status' => 1, 'read_time' => time()]);
            }
            foreach ($row as $r) {

                $rowModel = new Consume();
                $flow_staff_ids = explode(',', trim($r['flow_staff_ids'], ','));
                $check_staff_ids = explode(',', trim($r['check_staff_ids'], ','));
                $check_staff_ids[] = $staff->id;

                $diff = array_diff($flow_staff_ids, $check_staff_ids);
                if ($status == 1) {//审核通过
                    //记录
                    if (empty($diff)) {

                        $rowModel->save([
                            'check_status' => 2,
                            'check_staff_ids' => implode(',', $check_staff_ids)
                        ], ['id' => $r['id']]);
                        Message::addMessage($relation_type, $r['id'], $r['owner_staff_id'] ?? $r['staff_id'], $staff->id, '您提交的审批已审核通过！');
                    } else {
                        $diff = array_values($diff);
                        if ($relation_type == $model::CONSUME_TYPE) {
                            $rowModel->save(['check_staff_ids' => implode(',', $check_staff_ids), 'next_staff_id' => $diff[0], 'check_status' => 1], ['id' => $r['id']]);
                        } else {
                            $rowModel->save(['check_staff_ids' => implode(',', $check_staff_ids)], ['id' => $r['id']]);
                        }
                        $model::addExaminse($relation_type, $r['id'], $diff[0]);
                    }

                } else {

                    $rowModel->save(['check_status' => 3, 'check_staff_ids' => implode(',', $check_staff_ids)], ['id' => $r['id']]);
                    Message::addMessage($relation_type, $r['id'], $row['owner_staff_id'] ?? $row['staff_id'], $staff->id, '您提交的审批被拒绝！');
                }
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('审核成功');

    }

    //加签
    public function addExamineStaff()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');
        $staff_id = input('staff_id');
        $remark = input('remark/a');
        $model = new ExamineRecordModel();
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $rowModel = new Consume();
                break;
            case $model::CONTRACT_TYPE://合同
                $rowModel = new Contract();
                break;
            case $model::RECEIVABLES_TYPE://回款
                $rowModel = new Receivables();
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $rowModel = new AchievementRecords();
                break;
            case $model::PARTS_TYPE://零件
                $rowModel = new PartsStockReload();
                break;
            case $model::APPROVAL_TYPE://工作审批
                $rowModel = new Approval();
                break;
            case $model::QUOTE_TYPE://报价单
                $rowModel = new Quote();
                break;

            default:
                throw new Exception('参数错误');
        }
        $examine = ExamineRecordModel::where(['relation_type' => $relation_type, 'relation_id' => $relation_id, 'status' => 0])->find();
        ExamineRecordModel::where(['relation_type' => $relation_type, 'relation_id' => $relation_id, 'status' => 0])->update(['deletetime' => time()]);
        Message::setRead(Message::EXAMINE_TYPE, $examine['id']);

        $row = $rowModel->get($relation_id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        $row->save(['flow_staff_ids' => $staff_id]);
        $flow_staff_ids = explode(',', trim($staff_id, ','));
        $check_staff_ids = explode(',', trim(isset($row['check_staff_id']) ? $row['check_staff_id'] : $row['check_staff_ids'], ','));
        $diff = array_diff($flow_staff_ids, $check_staff_ids);
        $diff = array_values($diff);
        Message::setRead($relation_type, $relation_id);
        $model::addExaminse($relation_type, $relation_id, $diff[0]);

        $this->success('请求成功');
    }

    //审核人列表
    public function flowStaffList()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');

        $model = new ExamineRecordModel();
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $rowModel = new Consume();
                break;
            case $model::CONTRACT_TYPE://合同
                $rowModel = new Contract();
                break;
            case $model::RECEIVABLES_TYPE://回款
                $rowModel = new Receivables();
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $rowModel = new AchievementRecords();
                break;
            case $model::PARTS_TYPE://零件
                $rowModel = new PartsStockReload();
                break;
            case $model::APPROVAL_TYPE://工作审批
                $rowModel = new Approval();
                break;
            case $model::QUOTE_TYPE://报价单
                $rowModel = new Quote();
                break;

            case $model::INVOICE_TYPE://发票
                $rowModel = new Invoice();
                break;
            default:
                throw new Exception('参数错误');
        }
        $row = $rowModel->get($relation_id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        $flow_staff_id = explode(',', $row->flow_staff_ids);
        $staff = Staff::where(['id' => ['in', $flow_staff_id]])->column('id,name,img,post', 'id');
        $data = [];
        foreach ($flow_staff_id as $id) {
            $data[] = $staff[$id] ?? [];
        }
        $this->success('请求成功', $data);
    }


    /**
     * 获取审批列表
     */
    public function get_examine_list()
    {
        $limit = input("limit/d", 10);
        //合同审批，回款审批、业绩目标审批、办公审批 费用
        $relation_type = input('type');
        $examine_status = input('status', 0);
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        $sale_users = $this->auth->sale_users;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids,explode(',', $config_examine_admins[$this->auth->id]));
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            $sale_users = array_merge($sale_users,$config_sale_users);
        }
        switch ($relation_type) {
            case ExamineRecordModel::CONTRACT_TYPE://合同审批
                $ruleWhere = [];
                if ($this->auth->sale_users) {
                    $ruleWhere['sale_user'] = ['IN', implode(',', $sale_users)];
                }
                if ($examine_status == 1) {
                    //examine_status=1 or (examine_status=0 and (examine_index >= $this->examine_index ||  find_in_set($this->auth->id,examine_adminids) "))
                    // $ruleWhere['examine_status'] = ['exp', Db::raw('in ("1", "2") OR (examine_status="0" AND (examine_index >= '.($this->examine_index ? : 1).' OR FIND_IN_SET('.$this->auth->id.',`examine_adminids`)))')];
                    // //获取我审核的日志
                    // $logWhere = [
                    //     'relation_type' => 'goods_sale',
                    //     'admin_id' => $this->auth->id,
                    // ];
                    // $ids = Db::name('examine_log')->where($logWhere)->column('relation_id');
                    // if ($ids) {
                        // $ruleWhere['goods_sales.id'] = ['in', $ids];
                    // }
                    $ruleWhere['goods_sales.id'] = ['exp', Db::raw(' > 0 and FIND_IN_SET('.$this->auth->id.',check_history_uids)')];
                }else{
                    $ruleWhere['examine_status'] = '0';
                    if (!empty($this->first_children_ids)) {
                        if ($this->last_examine_indexs) {
                            $ruleWhere['goods_sales.id'] = ['exp', Db::raw('> 0 and ( (examine_index = 0 and sale_user in ('.implode(',', $this->first_children_ids).'))  OR (examine_index '.(count($this->last_examine_indexs) == 1 ? '='.$this->last_examine_indexs[0] : ' in ('.implode(',', $this->last_examine_indexs).')').' and sale_user in ('.implode(',', $sale_users).')))')];
                        } else {
                            $ruleWhere['examine_index'] = 0;
                        }
                    } else {
                        $ruleWhere['examine_index'] = count($this->last_examine_indexs) == 1 ? $this->last_examine_indexs[0] : ['in', $this->last_examine_indexs];
                    }

                    // $ruleWhere['examine_index'] = ['<', $this->examine_index ? : 1];
                    // if ($this->examine_index == count($this->flows['flow_items'])) {
                    //     $ruleWhere['examine_index'] = ['>', 0];
                    // }
                    // $ruleWhere['examine_adminids'] = ['not like', $this->auth->id];
                    $ruleWhere['examine_adminids'] = ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',examine_adminids) = 0')];
                }            
                $list = GoodsSales::with(['customers'])
                    ->where($ruleWhere)
                    ->order('goods_sales.id', 'DESC')
                    ->paginate($limit);
                    // echo $this->model->getLastSql();
                foreach ($list as $row) {
                    $row->visible(['id', 'purchase_code','purchase_time','sale_user','sale_user_name','customers.customer_name','customers_id', 'examine_status', 'examine_remark', 'examine_index', 'examine_adminids', 'createtime', 'relation_type', 'relation_id']);
                    $row->getRelation('customers')->visible(['customer_name']);
                }
                foreach ($list as $list_k=>$list_v){
                    //是否可以审核
                    $list[$list_k]['can_examine'] = false;
                    if ($list_v['examine_status'] == 0 && $list_v['examine_index'] < $this->examine_index ) {
                        $list[$list_k]['can_examine'] = true;
                    }
                    $examine_adminids = $list_v['examine_adminids'] ? explode(',', $list_v['examine_adminids']) : [];
                    if ($list_v['examine_status'] == 0 && ($list_v['examine_index'] >= $this->examine_index || in_array($this->auth->id,$examine_adminids))) {
                        $list[$list_k]['examine_status'] = 1;
                    }
                    $list[$list_k]['createtime'] = date('Y-m-d H:i:s', $list_v['createtime']);
                    $list[$list_k]['examine_remark'] = $list_v['examine_remark'] ?? '';
                    $list[$list_k]['relation_type'] = 'contract';
                    $list[$list_k]['relation_id'] = $list_v['id'];
                }
                break;
            case ExamineRecordModel::EXPENSE_TYPE:
                $wheres = [
                    'admin_id' => ['in', $adminids],
                ];
                if ($examine_status == 1) {
                    $wheres['id'] = ['exp', Db::raw(' > 0 and FIND_IN_SET('.$this->auth->id.',check_history_uids)')];
                }else{
                    $wheres['check_status'] = '1';
                    $wheres['check_step_sort'] = $this->examine_index - 1;//不可跨级
                    $wheres['check_uids'] = ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')];
                } 
                $list = Expense::where($wheres)->order('id DESC')->paginate($limit);
                // echo Expense::getLastSql();
                foreach ($list as $row) {
                    $row->visible(['id','expense_code','cost','income_month','start_time','subject_matter','end_time','admin_id','did','pay_status','remark','createtime','updatetime','check_status', 'admin_name', 'relation_type', 'relation_id']);
                }
                $adminList = [];
                if ($list) {
                    $adminids = array_column($list->items(),'admin_id');
                    $adminList = Admin::where('id','in',$adminids)->column('nickname','id');
                }
                foreach ($list as $list_k=>$list_v){
                    //是否可以审核
                    $list[$list_k]['can_examine'] = false;
                    if ($list_v['check_status'] == 1 && $list_v['check_step_sort'] == ($this->examine_index - 1)) {
                        $list[$list_k]['can_examine'] = true;
                    }
                    $examine_adminids = $list_v['check_uids'] ? explode(',', $list_v['check_uids']) : [];
                    if ($list_v['check_status'] == 1 && ($list_v['check_step_sort'] >= $this->examine_index || in_array($this->auth->id,$examine_adminids))) {
                        $list[$list_k]['check_status'] = 1;
                    }
                    if ($examine_status == 0) {
                        $list[$list_k]['check_status'] = $list_v['check_status'] == 1 ? 0 : $list_v['check_status'];
                    } else {
                        //获取最后一条审核日志
                        $last_status = Db::name('examine_log')->where(['relation_type' => 'expense', 'relation_id' => $list_v['id'], 'admin_id' => $this->auth->id])->order('id desc')->value('examine_status');
                        $list[$list_k]['check_status'] = $last_status == 0 ? 3 : 2;
                    }
                    $list[$list_k]['createtime'] = date('Y-m-d H:i:s', $list_v['createtime']);
                    $list[$list_k]['examine_remark'] = $list_v['check_remark'] ?? '';
                    $list[$list_k]['admin_name'] = $adminList[$list_v['admin_id']] ?? '';
                    $list[$list_k]['relation_type'] = 'expense';
                    $list[$list_k]['relation_id'] = $list_v['id'];
                }
                break;
            case ExamineRecordModel::SCORE_TYPE:
                $wheres = [
                    'admin_id' => ['in', $adminids],
                ];
                if ($examine_status == 1) {
                    $wheres['id'] = ['exp', Db::raw(' > 0 and FIND_IN_SET('.$this->auth->id.',check_history_uids)')];
                }else{
                    $wheres['check_status'] = '1';
                    if (!empty($this->children_ids)) {
                        if ($this->last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $this->children_ids).'))  OR (check_step_sort '.(count($this->last_examine_indexs) == 1 ? '='.$this->last_examine_indexs[0] : ' in ('.implode(',', $this->last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($this->last_examine_indexs) == 1 ? $this->last_examine_indexs[0] : ['in', $this->last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $this->examine_index - 1;//不可跨级
                    $wheres['check_uids'] = ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')];
                } 
                $list = ModelScoreApply::where($wheres)->order('id DESC')->paginate($limit);
                // echo Expense::getLastSql();
                foreach ($list as $row) {
                    $row->visible(['id','apply_code','total_score', 'add_score','admin_id','pay_status','remark','createtime','updatetime','check_status', 'admin_name', 'relation_type', 'relation_id']);
                }
                $adminList = [];
                if ($list) {
                    $adminids = array_column($list->items(),'admin_id');
                    $adminList = Admin::where('id','in',$adminids)->column('nickname','id');
                }
                foreach ($list as $list_k=>$list_v){
                    //是否可以审核
                    $list[$list_k]['can_examine'] = false;
                    if ($list_v['check_status'] == 1 && $list_v['check_step_sort'] == ($this->examine_index - 1)) {
                        $list[$list_k]['can_examine'] = true;
                    }
                    $examine_adminids = $list_v['check_uids'] ? explode(',', $list_v['check_uids']) : [];
                    if ($list_v['check_status'] == 1 && ($list_v['check_step_sort'] >= $this->examine_index || in_array($this->auth->id,$examine_adminids))) {
                        $list[$list_k]['check_status'] = 1;
                    }
                    if ($examine_status == 0) {
                        $list[$list_k]['check_status'] = $list_v['check_status'] == 1 ? 0 : $list_v['check_status'];
                    } else {
                        //获取最后一条审核日志
                        $last_status = Db::name('examine_log')->where(['relation_type' => 'score', 'relation_id' => $list_v['id'], 'admin_id' => $this->auth->id])->order('id desc')->value('examine_status');
                        $list[$list_k]['check_status'] = $last_status == 0 ? 3 : 2;
                    }
                    $list[$list_k]['createtime'] = date('Y-m-d H:i:s', $list_v['createtime']);
                    $list[$list_k]['examine_remark'] = $list_v['check_remark'] ?? '';
                    $list[$list_k]['admin_name'] = $adminList[$list_v['admin_id']] ?? '';
                    $list[$list_k]['relation_type'] = 'score';
                    $list[$list_k]['relation_id'] = $list_v['id'];
                }
                break;
            case ExamineRecordModel::COMMONSEAL_TYPE:
                $wheres = [
                    'admin_id' => ['in', $adminids],
                ];
                if ($examine_status == 1) {
                    $wheres['id'] = ['exp', Db::raw(' > 0 and FIND_IN_SET('.$this->auth->id.',check_history_uids)')];
                }else{
                    $wheres['check_status'] = '1';
                    if (!empty($this->children_ids)) {
                        if ($this->last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $this->children_ids).'))  OR (check_step_sort '.(count($this->last_examine_indexs) == 1 ? '='.$this->last_examine_indexs[0] : ' in ('.implode(',', $this->last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($this->last_examine_indexs) == 1 ? $this->last_examine_indexs[0] : ['in', $this->last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $this->examine_index - 1;//不可跨级
                    $wheres['check_uids'] = ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')];
                } 
                $list = Commonseal::where($wheres)->order('id DESC')->paginate($limit);
                // echo Expense::getLastSql();
                foreach ($list as $row) {
                    $row->visible(['id','common_seal','usedeatil', 'admin_id','customer','remark','createtime','updatetime','check_status', 'admin_name', 'relation_type', 'relation_id']);
                }
                $adminList = [];
                if ($list) {
                    $adminids = array_column($list->items(),'admin_id');
                    $adminList = Admin::where('id','in',$adminids)->column('nickname','id');
                }
                foreach ($list as $list_k=>$list_v){
                    //是否可以审核
                    $list[$list_k]['can_examine'] = false;
                    if ($list_v['check_status'] == 1 && $list_v['check_step_sort'] == ($this->examine_index - 1)) {
                        $list[$list_k]['can_examine'] = true;
                    }
                    $examine_adminids = $list_v['check_uids'] ? explode(',', $list_v['check_uids']) : [];
                    if ($list_v['check_status'] == 1 && ($list_v['check_step_sort'] >= $this->examine_index || in_array($this->auth->id,$examine_adminids))) {
                        $list[$list_k]['check_status'] = 1;
                    }
                    if ($examine_status == 0) {
                        $list[$list_k]['check_status'] = $list_v['check_status'] == 1 ? 0 : $list_v['check_status'];
                    } else {
                        //获取最后一条审核日志
                        $last_status = Db::name('examine_log')->where(['relation_type' => ExamineRecordModel::COMMONSEAL_TYPE, 'relation_id' => $list_v['id'], 'admin_id' => $this->auth->id])->order('id desc')->value('examine_status');
                        $list[$list_k]['check_status'] = $last_status == 0 ? 3 : 2;
                    }
                    $list[$list_k]['createtime'] = date('Y-m-d H:i:s', $list_v['createtime']);
                    $list[$list_k]['examine_remark'] = $list_v['check_remark'] ?? '';
                    $list[$list_k]['admin_name'] = $adminList[$list_v['admin_id']] ?? '';
                    $list[$list_k]['relation_type'] = ExamineRecordModel::COMMONSEAL_TYPE;
                    $list[$list_k]['relation_id'] = $list_v['id'];
                }
                break;
        }
        
        $this->success('请求成功', $list);
    }
}
